﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace weba.Sales
{
    public partial class PurchaseOrderHeaderCreatFromNeedMaterial : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                //实例上一个窗体SalesOrderListForPurchaseOrderHeader.aspx
                //SalesOrderListForPurchaseOrderHeader newWeb = (SalesOrderListForPurchaseOrderHeader)Context.Handler; ;
                //this.lblstrArrSalesOrderID.Text = newWeb.strArrSalesOrderID;
                //this.lblstrArrSalesOrderID.Text = "1,2";

                if (Request.QueryString["NeedMaterialID"] != null)
                {
                    if (mk.IsNumber(Request.QueryString["NeedMaterialID"].ToString()))
                    {
                        //用一个隐藏Label保存传递过来的ID
                        this.lblNeedMaterialID.Text = Request.QueryString["NeedMaterialID"].ToString();
                    }
                    else
                    {
                        mk.Alert("参数错误！");
                    }
                }
                else
                {
                    mk.Alert("参数错误！");
                }

                //绑定订单列表
                //this.BindSalesOrder();


                //设置经办人信息
                Accounts_Users currentUser = mk.l.Accounts_Users.FirstOrDefault();
                this.lblManagerTrueName.Text = currentUser.TrueName;
                this.lblManagerUserName.Text = currentUser.UserName;
                //设置根部门ID
                var bllDept = mk.l.Accounts_Department.ToList();
                this.lblRootDepartmentID.Text = bllDept.Single(h => h.ClassID == (int.Parse(currentUser.DepartmentID))).RootID.ToString();
                //给日期输入框添加只读属性，不能在属性里直接设置，不然会取不到值
                this.txtDateOrder.Attributes["readonly"] = "true";
                this.txtDateOrder.Date = System.DateTime.Now;
                //显示订单概况
                this.ShowSalesOrderHeaderInfo();
            }
        }
        private void ShowSalesOrderHeaderInfo()
        {
            var bllNeedHeader = mk.l.Sales_NeedMaterialHeader.ToList();
            Sales_NeedMaterialHeader mNeedHeader = bllNeedHeader.Where(h => h.NeedMaterialID == int.Parse(this.lblNeedMaterialID.Text)).FirstOrDefault();


            if (mNeedHeader != null)
            {
                //判断是否是本店的订单
                if (int.Parse(this.lblRootDepartmentID.Text) == mNeedHeader.RootDepartmentID)
                {
                    //先判断一下是否已经提交 没提交的就别管了
                    if (mNeedHeader.StatusSubmit == "2")
                    {
                        this.lblSalesOrderID.Text = mNeedHeader.SalesOrderID.ToString();
                        var bllOrderHeader = mk.l.Sales_SalesOrderHeader.ToList();
                        Sales_SalesOrderHeader mOrderHeader = bllOrderHeader.Where(h => h.SalesOrderID == mNeedHeader.SalesOrderID).FirstOrDefault();
                        if (mOrderHeader != null)
                        {
                            //判断是否已经订货，如果已经订货，则转到订货单编辑页面
                            if (mNeedHeader.StatusPurchaseMaterial == "1")
                            {
                                this.lblSalesOrderNumber.Text = mOrderHeader.SalesOrderNumber;
                                this.lblNotesOrder.Text = mOrderHeader.NotesOrder;
                                var bllUser = mk.l.Accounts_Users.ToList();
                                Accounts_Users mUser = bllUser.Where(h => h.UserName == mOrderHeader.Designer).First();
                                this.lblDesigner.Text = mUser.TrueName;
                                this.lblDateOrder.Text = mNeedHeader.DateOrder.ToString();
                                this.BindNeedMaterialDetail();
                            }
                            else
                            {
                                Response.Redirect("PurchaseOrderHeaderEditFromNeedMaterial.aspx?NeedMaterialID=" + this.lblNeedMaterialID.Text, false);
                            }
                        }
                        else
                        {
                            mk.Alert("参数错误！", "NeedMaterialListForPurchaseOrderHeader.aspx");
                        }
                    }
                    else
                    {
                        mk.Alert("此用料单尚未提交！", "NeedMaterialListForPurchaseOrderHeader.aspx");
                    }
                }
                else
                {
                    mk.Alert("只能操作本店的订单！");
                }
            }
            else
            {
                mk.Alert("参数错误！", "NeedMaterialListForPurchaseOrderHeader.aspx");
            }
        }

        private void BindNeedMaterialDetail()
        {
            var bll = mk.l.Sales_NeedMaterialDetailandSales_Material.ToList();
            var ds = bll.Where(h => h.NeedMaterialID.ToString() == this.lblNeedMaterialID.Text);
            this.myGridViewNeedMaterialDetail.DataSource = ds;
            this.myGridViewNeedMaterialDetail.DataBind();
        }
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblManufacturerName = (Label)(e.Row.FindControl("lblManufacturerName"));
                var bllManufacturer = mk.l.Sales_Manufacturer.ToList();
                Sales_Manufacturer mManufacturer = bllManufacturer.Where(h => h.ManufacturerID == int.Parse(this.myGridView.DataKeys[e.Row.RowIndex].Values["ManufacturerID"].ToString())).FirstOrDefault();
                lblManufacturerName.Text = mManufacturer.ManufacturerName;

            }
        }
        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                mk.Alert("生成订货单成功！将返回到订货单列表", "PurchaseOrderHeaderList.aspx");
            }
        }
        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (this.myGridView.Rows.Count > 0)
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
        }

        /// <summary>
        /// Handles the RowDeleting event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewDeleteEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //this.lblMsg2.Text = string.Empty;
            //UART.BLL.Sales.PurchaseOrderHeader bll = new UART.BLL.Sales.PurchaseOrderHeader();
            //try
            //{
            //    bll.Delete(int.Parse(this.myGridView.DataKeys[e.RowIndex].Values["PurchaseOrderID"].ToString()));
            //    this.BindPurchaseOrderHeader();
            //    //提交事务
            //    ContextUtil.SetComplete();
            //}
            //catch (Exception ex)
            //{
            //    //撤销事务
            //    ContextUtil.SetAbort();
            //    this.lblMsg2.Text = "删除失败！错误信息：" + ex.Message;
            //}
        }
        protected void myGridViewNeedMaterialDetail_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Label lblManufacturerCode = (Label)(e.Row.FindControl("lblManufacturerCode"));
                Label lblManufacturerName = (Label)(e.Row.FindControl("lblManufacturerName"));
                var bllManufacturer = mk.l.Sales_Manufacturer.ToList();
                Sales_Manufacturer mManufacturer = bllManufacturer.Where(h => h.ManufacturerID == int.Parse(this.myGridViewNeedMaterialDetail.DataKeys[e.Row.RowIndex].Values["ManufacturerID"].ToString())).FirstOrDefault();
                //lblManufacturerCode.Text = mManufacturer.ManufacturerCode;
                lblManufacturerName.Text = mManufacturer.ManufacturerName;
            }
        }
        /// 生成订货单概况、订货单明细等内容
        /// </summary>
        protected void btnCreatPurchaseOrder_Click(object sender, EventArgs e)
        {
            
            //实例化用料表表头业务逻辑处理类
            var bllNeedHeader =
                  mk.l.Sales_NeedMaterialHeader.ToList();
            //根据当前的用料表ID号得到用料表实例
      Sales_NeedMaterialHeader mNeedHeader = 
                bllNeedHeader.Where(h=>h.NeedMaterialID==int.Parse(this.lblNeedMaterialID.Text)).FirstOrDefault();
            if (mNeedHeader != null)
            {
                //判断是否已经订货，如果已经订货，则转到订货单编辑页面
                if (mNeedHeader.StatusPurchaseMaterial == "1")
                {
                    try
                    {
                        this.lblMsg2.Text = string.Empty;
                        //取得选中订单中的不同厂家ID 为每个厂家添加订货单
                      var bll = 
                            mk.l.Sales_NeedMaterialDetail.ToList();
                       var dsManufacturerID = 
                            bll.Where(h=>h.NeedMaterialID==
                            (int.Parse(this.lblNeedMaterialID.Text))).Distinct().Select(y=>y.ManufacturerID).Distinct();
                        //订货单概况类
                    var bllHeader = 
                            mk.l.Sales_PurchaseOrderHeader.ToList();
                        Sales_PurchaseOrderHeader mHeader = 
                         new  Sales_PurchaseOrderHeader();
                        //订货单明细类
                       var bllDetail = 
                            mk.l.Sales_PurchaseOrderDetail.ToList();
                Sales_PurchaseOrderDetail mDetail = 
                            new Sales_PurchaseOrderDetail();
                        int PurchaseOrderID = 0;
                        //为每个厂家添加订货单和订货单明细
                        foreach (var drManufacturerID in 
                            dsManufacturerID)
                        {
                            //添加订货单概况
                            mHeader = new Sales_PurchaseOrderHeader();
                            int ManufacturerID = 
                                int.Parse(drManufacturerID.ToString());
                            mHeader.DateOrder = Convert.ToDateTime(this.txtDateOrder.Date);
                            mHeader.DatePayment = Convert.ToDateTime("9999-1-1");
                            mHeader.Manager = this.lblManagerUserName.Text;
                            mHeader.ManufacturerID = ManufacturerID;
                            mHeader.ModifiedDate = System.DateTime.Now;
                            //设置订货单所属的用料单ID
                            mHeader.NeedMaterialID = 
                                int.Parse(this.lblNeedMaterialID.Text);
                            //先将订货单编号暂时设置为空
                            mHeader.OrderNumber = string.Empty;
                            mHeader.RootDepartmentID = 
                                int.Parse(this.lblRootDepartmentID.Text);
                            mHeader.StatusArrival = "0";
                            mHeader.StatusPayment = "0";
                            //订货单金额暂时设置为0
                            mHeader.SubTotal = bll.Where(y => y.ManufacturerID == drManufacturerID).Sum(u => u.Subtotal);
                            //设置订货单所属的订单ID
                            mHeader.SalesOrderID = 
                                int.Parse(this.lblSalesOrderID.Text);
                            //添加订货单概况 获取订货单概况ID
                            
                            mk.l.Sales_PurchaseOrderHeader.InsertOnSubmit(mHeader);
                  mk.l.SubmitChanges();
                            PurchaseOrderID =mHeader.PurchaseOrderID;
                     
                            //添加订货单明细
                            var dsMaterialID = bll.Where(h => h.NeedMaterialID == (int.Parse(this.lblNeedMaterialID.Text)) & h.ManufacturerID == ManufacturerID).ToList(); 
                         
                            //添加订货单材料列表
                          
                            foreach (Sales_NeedMaterialDetail drMaterialID in dsMaterialID)
                            {

                                mDetail = new Sales_PurchaseOrderDetail();
                                int MaterialID = 
                                    int.Parse(drMaterialID.MaterialID.ToString());
                                mDetail.CostUnitPrice = drMaterialID.UnitPrice;
                                mDetail.DateArrival = Convert.ToDateTime("9999-1-1");
                                mDetail.MaterialID = MaterialID;
                                mDetail.ModifiedDate = System.DateTime.Now;
                                mDetail.PurchaseOrderID = PurchaseOrderID;
                                mDetail.StatusArrival = "0";
                                mDetail.Subtotal = drMaterialID.Subtotal;
                                //计算指定订单指定材料的订购数量
                                mDetail.Quantity = 
                                 //   bll.Where((h=>h.NeedMaterialID==(int.Parse(this.lblNeedMaterialID.Text))&h.MaterialID== MaterialID)).FirstOrDefault().Quantity;
                                 drMaterialID.Quantity;
                                //把入库仓库ID设置为0
                                mDetail.InventoryManager = string.Empty;
                                mDetail.LocationID = 0;
                                //添加订货单明细
                               
                        mk.l.Sales_PurchaseOrderDetail.InsertOnSubmit(mDetail);

                        mk.l.SubmitChanges();
                            
                            }
                        }
                        //把所选的用料单的StatusPurchaseMaterial设置为2
          Sales_NeedMaterialHeader      f =  bllNeedHeader.Single(h=>h.NeedMaterialID==(int.Parse(this.lblNeedMaterialID.Text)));
                           f.StatusPurchaseMaterial="2";
                        mk.l.SubmitChanges();
                        //判断订单的订货状态 
                     string StatusPurchaseMaterial= mk.GetStatusPurchaseMaterial(int.Parse(this.lblSalesOrderID.Text));
                     var bllOrderHeader = 
                           mk.l.Sales_SalesOrderHeader.ToList();
            Sales_SalesOrderHeader r=            bllOrderHeader.Single(h=>h.SalesOrderID==
                            (int.Parse(this.lblSalesOrderID.Text))); 
                        r.StatusPurchaseMaterial=    StatusPurchaseMaterial;                  
                          
                        //将生成按钮设置为不可用 防止重复添加
                        this.btnCreatPurchaseOrder.Enabled = false;
                        this.BindPurchaseOrderHeader();
                        this.lblMsg2.Visible = true;
                        this.lblMsg2.Text = "生成订货单后，请核对订货单明细，设置订货单编号！";
                        //提交事务
                      //  ContextUtil.SetComplete();
                    }
                    catch (Exception ex)
                    {
                        //撤销事务
                        //ContextUtil.SetAbort();
                        this.lblMsg2.Visible = true;
                        this.lblMsg2.Text = "生成错误！错误信息：" + ex.Message;
                    }
                }
                else
                {
                    Response.Redirect("PurchaseOrderHeaderEditFromNeedMaterial.aspx?NeedMaterialID=" + 
                        this.lblNeedMaterialID.Text, false);
                }
            }
            else
            {
                this.lblMsg2.Visible = true;
                this.lblMsg2.Text = "生成错误！此用料单不存在或已被删除";
            }
        }

        /// <summary>
        /// Binds the purchase order header.绑定添加的订货单列表
        /// </summary>
        private void BindPurchaseOrderHeader()
        {
            var bll = mk.l.Sales_PurchaseOrderHeader.ToList();
            var ds = bll.Where(h => h.NeedMaterialID.ToString() == this.lblNeedMaterialID.Text);
            this.myGridView.DataSource = ds;
            this.myGridView.DataBind();
        }
    }
}